/**
 * @description:
 * @file: listen.ts
 * @author: Evan
 * @date: 2025.04.10 11:13:20
 * @week: 周四
 * @version: V
 * */

import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
NProgress.configure({ showSpinner: false, parent: '#app' })

import ApiEmiter from '@/api/axios/emiter'
import { Message } from '@/utils/element'
import { useUserStore } from '@/stores'
import type { ApiConfig } from './axios/type'

const eLoading = (
  options: Parameters<typeof ElLoading.service>[0] = {
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)'
  }
) => {
  return ElLoading.service(options)
}

// 请求加载弹窗
const loadingWeakMap = new WeakMap()

// 获取加载配置
const getLoadingOpts = (): {
  style: Parameters<typeof ElLoading.service>[0]
  el?: ReturnType<typeof ElLoading.service>
} => {
  return {
    style: {
      lock: true,
      text: 'Loading',
      // spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.3)'
    }
  }
}

// 请求开始
ApiEmiter.on('api:start', (config: ApiConfig) => {
  NProgress.start()
  const loading = config.loading
  if (loading) {
    const axiosLoding = getLoadingOpts()
    if (axiosLoding.style) {
      axiosLoding.style.target =
        loading instanceof HTMLElement
          ? loading
          : typeof loading === 'string'
          ? (document.querySelector(loading) as HTMLElement)
          : void 0
    }
    axiosLoding.el = eLoading(axiosLoding.style)
    // 缓存
    loadingWeakMap.set(config, axiosLoding)
  }
})

// 请求结束
ApiEmiter.on('api:end', (config: ApiConfig) => {
  NProgress.done()
  config.loading && loadingWeakMap.get(config).el?.close()
})

// 无权限
ApiEmiter.on('api:un_auth', () => {
  // 返回登录
  useUserStore().resetToken()
})

// 异常
ApiEmiter.on('api:error', (config: ApiConfig, er: any) => {
  console.log(er)
  if (er.code) {
    er.code = parseInt(er.code, 10)
    er.data = er.data || ''
    if (er.code !== 0) {
      // 控制台输出信息，方便提交后台排错
      console.info(
        `错误编码：${er.code}\n错误信息：${er.message}\n接口地址：${
          config.url
        }\n输入参数：${JSON.stringify(config.data || config.params)}`
      )
    }
  }
  Message(er?.message || '链接错误', 'error')
})
